﻿package TaskStructure 
{
	import flash.display.MovieClip;
	import flash.events.Event;
		
	/** The highest level container for this project, a task wraps all items. */
	public class Section extends MovieClip
	{
		// private variables
		private var isFinalFinal:Boolean;
		private var currentItem:int=0;
		private var startingProblemNumber:int=0;
		// private objects
		private var logWriter:LogWriter;
		private var sectionXML:XML, problemXML:XML, contextXML:XML, imagesXML:XML, errorsXML:XML;
		private var itemsxml:XMLList;
		private var item:WordProblemItem;
		
		public function Section(logWriter:LogWriter, startingProblemNumber:int, sectionXML:XML, problemXML:XML, contextXML:XML, imagesXML:XML, errorsXML:XML, isFinalFinal:Boolean)
		{
			this.logWriter = logWriter;
			this.currentItem = startingProblemNumber-1;
			this.sectionXML = sectionXML;
			this.problemXML = problemXML;
			this.contextXML = contextXML;
			this.imagesXML = imagesXML;
			this.errorsXML = errorsXML;
			this.isFinalFinal = isFinalFinal;
			this.addEventListener(Event.ADDED, handleAdded);
		}
		private function handleAdded (event:Event):void
		{
			this.removeEventListener(Event.ADDED, handleAdded);
			this.graphics.drawRect(0,0,this.parent.width, this.parent.height);
			
			//itemsxml = sectionXML..item.(attribute("complete") != "true");
			itemsxml = sectionXML..item;
			newItem();
		}
		/** Open a new item */
		private function newItem():void
		{
			if (currentItem < itemsxml.length())
			{
				item = new WordProblemItem(logWriter, sectionXML..options[0], itemsxml[currentItem], problemXML, contextXML, imagesXML, errorsXML, currentItem);
				item.addEventListener(Event.COMPLETE, handleItemComplete);
				item.addEventListener(Event.CANCEL, handleItemCancel);
				this.addChild(item);
			} else
			{
				this.dispatchEvent(new Event(Event.COMPLETE));				
			}			
		}
		/** The item is complete, iterate and try another */
		private function handleItemComplete(event:Event):void
		{
			item.removeEventListener(Event.COMPLETE, handleItemComplete);
			item.removeEventListener(Event.CANCEL, handleItemCancel);
			// update xml
			var node:XML, pnode:XML;
			var isFirst:Boolean, isFinal:Boolean;
			if (currentItem == itemsxml.length()-1){isFinal=true;} else {isFinal=false;}
			
			currentItem++;
			this.removeChild(item);
			newItem();
		}
			
		/** The item is cancelled, go to previous */
		private function handleItemCancel(event:Event):void
		{
			item.removeEventListener(Event.COMPLETE, handleItemComplete);
			item.removeEventListener(Event.CANCEL, handleItemCancel);
			this.removeChild(item);
			if (currentItem > 0) currentItem--;
			newItem();
		}

	}
}